package com.meiyuetao.myt.pub.web.action;

import java.sql.ResultSet;
import java.sql.SQLException;

import lab.s2jh.core.web.SimpleController;

import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

public class AbroadPartnerController extends SimpleController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private Integer size;// 返回条数

    /**
     * 用户浏览过的商品
     * 
     * @return
     */
    public HttpHeaders seq() {
        // Map<String, Object> jsonMap = Maps.newHashMap();
        // jsonMap.put("sequence", sequence(size));
        // setModel(jsonMap);
        setModel(sequence(size));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders region() {
        setModel(getAllRegionName());
        return buildDefaultHttpHeaders();
    }

    /**
     * 查询 用户最近浏览过的商品
     * 
     * @param cid
     *            客户SID
     * @param size
     *            返回商品条数
     * @return
     */
    @SuppressWarnings("deprecation")
    public String sequence(Integer size) {
        size = size == null ? 1 : size;// 默认TOP5
        String sql = "SELECT NEXT VALUE FOR abroad_partner";
        String sequence = "";
        for (int i = 0; i < size; i++) {
            Long seq = jdbcTemplate.queryForLong(sql);
            sequence += seq + ",";
        }
        return sequence.substring(0, sequence.length() - 1);
    }

    /**
     * 查询 用户最近浏览过的商品
     * 
     * @param cid
     *            客户SID
     * @param size
     *            返回商品条数
     * @return
     */
    public String getAllRegionName() {
        String sql = "SELECT r.name FROM iyb_region r";
        final StringBuilder region = new StringBuilder();

        jdbcTemplate.query(sql, new RowCallbackHandler() {

            @Override
            public void processRow(ResultSet rs) throws SQLException {
                region.append(rs.getString("name") + " ");
            }
        });
        return region.toString();
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }
}